package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.BusinessException;
import com.sky.exception.LoginRequiredException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.Result;
import com.sky.service.ShoppingCartService;
import com.sky.mapper.ShoppingCartMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author 86158
 * @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
 * @createDate 2025-08-24 19:01:17
 */
@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService{

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 添加商品到购物车（事务保证：防止数量更新/新增时数据不一致）
     */
    @Override
    @Transactional
    public Result<ShoppingCart> add(ShoppingCartDTO shoppingCartDTO) {
        // 1. 校验用户是否已登录（关键！避免user_id为空）
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            // 抛自定义异常，全局异常处理器会捕获并返回"请先登录"
            log.warn("用户未登录");
            throw new LoginRequiredException("添加购物车需先登录");

        }

        // 2. 构建查询条件：用户ID + 菜品/套餐ID + 口味（确保同一商品不同口味算不同记录）
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                // 菜品ID不为空时，匹配菜品ID
                .eq(shoppingCartDTO.getDishId() != null, ShoppingCart::getDishId, shoppingCartDTO.getDishId())
                // 套餐ID不为空时，匹配套餐ID
                .eq(shoppingCartDTO.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCartDTO.getSetmealId())
                // 口味不为空时，匹配口味（如"微辣"和"特辣"是不同记录）
                .eq(shoppingCartDTO.getDishFlavor() != null, ShoppingCart::getDishFlavor, shoppingCartDTO.getDishFlavor());

        // 3. 查询购物车中是否已存在该商品（MyBatis-Plus getOne()简化，避免List操作）
        ShoppingCart existingCart = this.getOne(queryWrapper);

        // 4. 已存在：数量+1并更新
        if (existingCart != null) {
            existingCart.setNumber(existingCart.getNumber() + 1);
            log.info("购物车已存在该商品，数量+1");
            this.updateById(existingCart);
            return Result.success(existingCart); // 返回更新后的完整记录
        }
        log.info("购物车不存在该商品，新增");
        // 5. 不存在：新增购物车记录
        ShoppingCart newCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO, newCart);
        newCart.setUserId(userId);
        newCart.setNumber(1); // 公共逻辑：默认数量1
        newCart.setCreateTime(LocalDateTime.now()); // 公共逻辑：当前时间

        // 5.1 区分菜品/套餐，补充名称、图片、价格，并校验状态
        if (shoppingCartDTO.getDishId() != null) {
            log.info("添加购物车菜品");
            // 查询菜品信息
            Dish dish = dishMapper.selectById(shoppingCartDTO.getDishId());
            if (dish == null) {
                log.warn("菜品不存在");
                throw new BusinessException("该菜品不存在");
            }
            // 校验菜品是否起售（1-起售，0-停售）
            if (dish.getStatus() == 0) {
                log.warn("菜品已停售");
                throw new BusinessException("该菜品已停售，无法加入购物车");
            }
            log.info("菜品起售");
            // 填充菜品信息到购物车
            newCart.setName(dish.getName());
            newCart.setImage(dish.getImage());
            newCart.setAmount(dish.getPrice()); // 单价（后续计算总价=数量*单价）
        } else if (shoppingCartDTO.getSetmealId() != null) {
            log.info("添加购物车套餐");
            // 查询套餐信息
            Setmeal setmeal = setmealMapper.selectById(shoppingCartDTO.getSetmealId());
            if (setmeal == null) {
                log.warn("套餐不存在");
                throw new BusinessException("该套餐不存在");
            }
            // 校验套餐是否起售
            if (setmeal.getStatus() == 0) {
                log.warn("套餐已停售");
                throw new BusinessException("该套餐已停售，无法加入购物车");
            }
            log.info("套餐起售");
            // 填充套餐信息到购物车
            newCart.setName(setmeal.getName());
            newCart.setImage(setmeal.getImage());
            newCart.setAmount(setmeal.getPrice());
        } else {
            log.warn("请选择菜品或套餐");
            throw new BusinessException("请选择菜品或套餐");
        }

        // 5.2 保存到数据库（MyBatis-Plus会自动填充主键到newCart）
        this.save(newCart); // 保存
        return Result.success(newCart); // 返回包含主键的完整记录
    }
    /**
     * 删除购物车商品某个商品
     *
     * */

    @Override
    public Result<String> sub(ShoppingCartDTO shoppingCartDTO) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        if (shoppingCartDTO.getDishId() != null) {
            queryWrapper.eq(ShoppingCart::getDishId,shoppingCartDTO.getDishId());
        }
        if (shoppingCartDTO.getSetmealId() != null) {
            queryWrapper.eq(ShoppingCart::getSetmealId,shoppingCartDTO.getSetmealId());
        }
        if (shoppingCartDTO.getDishFlavor() != null) {
            queryWrapper.eq(ShoppingCart::getDishFlavor,shoppingCartDTO.getDishFlavor());
        }
        ShoppingCart shoppingCart = shoppingCartMapper.selectOne(queryWrapper);
        if (shoppingCart != null) {
            if (shoppingCart.getNumber() == 1) {
                shoppingCartMapper.deleteById(shoppingCart.getId());
            } else {
                shoppingCart.setNumber(shoppingCart.getNumber() - 1);
                shoppingCartMapper.updateById(shoppingCart);
            }
            return Result.success();
        }
        return Result.error("购物车为空");
    }
}